package com.jmlambert.droidmc;

import java.io.DataInputStream;
import java.net.InetAddress;
import java.net.Socket;

import com.jmlambert.droidmc.R;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.GestureDetector;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;


public class MainActivity extends Activity {
    /** Called when the activity is first created. */
	Thread cThread = null;
	String lastUpdate = "";
    // Need handler for callbacks to the UI thread
    final Handler mHandler = new Handler();
    TextView debugInfoView = null;
    StatusThread statusClient;
    public static final int MENU_SETTINGS = 1;
    public static final int MENU_QUIT = 2;
    public static Activity me = null;
    private static final int SWIPE_MIN_DISTANCE = 120;    
    private static final int SWIPE_MAX_OFF_PATH = 250;    
    private static final int SWIPE_THRESHOLD_VELOCITY = 200;    
    private GestureDetector gestureDetector;    
    View.OnTouchListener gestureListener;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        debugInfoView = (TextView)findViewById(R.id.debuginfo);
        Button startDebugButton = (Button)findViewById(R.id.startdebug);
        Button stopDebugButton = (Button)findViewById(R.id.stopdebug);
        Button upButton = (Button)findViewById(R.id.upbutton);
        Button downButton = (Button)findViewById(R.id.downbutton);
        Button leftButton = (Button)findViewById(R.id.leftbutton);
        Button rightButton = (Button)findViewById(R.id.rightbutton);
        Button backButton = (Button)findViewById(R.id.backbutton);
        Button okButton = (Button)findViewById(R.id.okbutton);
        ImageButton skipbackButton = (ImageButton)findViewById(R.id.skipbackbutton);
        ImageButton rewindButton = (ImageButton)findViewById(R.id.rewindbutton);
        ImageButton playButton = (ImageButton)findViewById(R.id.playbutton);
        ImageButton ffButton = (ImageButton)findViewById(R.id.ffbutton);
        ImageButton skipforwardButton = (ImageButton)findViewById(R.id.skipforwardbutton);
        TextView slideContent = (TextView) findViewById(R.id.slidecontent);
        startDebugButton.setOnClickListener(mGoListener);
        stopDebugButton.setOnClickListener(mGoListener);
        upButton.setOnClickListener(mGoListener);
        downButton.setOnClickListener(mGoListener);
        leftButton.setOnClickListener(mGoListener);
        rightButton.setOnClickListener(mGoListener);
        backButton.setOnClickListener(mGoListener);
        okButton.setOnClickListener(mGoListener);
        skipbackButton.setOnClickListener(mGoListener);
        rewindButton.setOnClickListener(mGoListener);
        playButton.setOnClickListener(mGoListener);
        ffButton.setOnClickListener(mGoListener);
        skipforwardButton.setOnClickListener(mGoListener);

        
		 //Gesture detection 
		gestureDetector = new GestureDetector(new MyGestureDetector());
		gestureListener = new View.OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				if (gestureDetector.onTouchEvent(event)) {
					return true;
				}
				return false;
			}
		};
		
		slideContent.setOnTouchListener(gestureListener);
		slideContent.setOnClickListener(mGoListener);
        
        me = this;
    }
    
    @Override
    protected void onStop() {
    	super.onStop();
    	if(statusClient != null && statusClient.isAlive())
    		statusClient.stop();
    }

    /* Creates the menu items */
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(0, MENU_SETTINGS, 0, "Settings");
        menu.getItem(0).setIcon(android.R.drawable.ic_menu_preferences);
        menu.add(0, MENU_QUIT, 1, "Quit");
        menu.getItem(1).setIcon(android.R.drawable.ic_menu_close_clear_cancel);
        return true;
    }

    /* Handles item selections */
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case MENU_SETTINGS:
        	Intent settingsActivity = new Intent(getBaseContext(), Preferences.class);
      		startActivity(settingsActivity);
            return true;
        case MENU_QUIT:
        	this.finish();
            return true;
        }
        return false;
    }

    private OnClickListener mGoListener = new OnClickListener()
    {
        public void onClick(View v)
        {
        	if(v.getId() == R.id.startdebug)
        	{
        		if(statusClient == null || !statusClient.isAlive())
        		{
        			statusClient = new StatusThread();
        			statusClient.start();
        		}
        	}
        	else if(v.getId() == R.id.stopdebug)
        	{
        		if(statusClient != null && statusClient.isAlive())
        			statusClient.interrupt();
        	}
        	else if(v.getId() == R.id.upbutton)
        	{
        		TCPClient.message = "button-up";
        		Thread newClientThread = new Thread(new TCPClient());
        		newClientThread.start();
        	}
        	else if(v.getId() == R.id.downbutton)
        	{
        		TCPClient.message = "button-down";
        		Thread newClientThread = new Thread(new TCPClient());
        		newClientThread.start();
        	}
        	else if(v.getId() == R.id.leftbutton)
        	{
        		TCPClient.message = "button-left";
        		Thread newClientThread = new Thread(new TCPClient());
        		newClientThread.start();
        	}
        	else if(v.getId() == R.id.rightbutton)
        	{
        		TCPClient.message = "button-right";
        		Thread newClientThread = new Thread(new TCPClient());
        		newClientThread.start();
        	}
        	else if(v.getId() == R.id.backbutton)
        	{
        		TCPClient.message = "button-back";
        		Thread newClientThread = new Thread(new TCPClient());
        		newClientThread.start();
        	}
        	else if(v.getId() == R.id.okbutton)
        	{
        		TCPClient.message = "button-ok";
        		Thread newClientThread = new Thread(new TCPClient());
        		newClientThread.start();
        	}
        	else if(v.getId() == R.id.skipbackbutton)
        	{
        		TCPClient.message = "button-skipback";
        		Thread newClientThread = new Thread(new TCPClient());
        		newClientThread.start();
        	}
        	else if(v.getId() == R.id.rewindbutton)
        	{
        		TCPClient.message = "button-rew";
        		Thread newClientThread = new Thread(new TCPClient());
        		newClientThread.start();
        	}
        	else if(v.getId() == R.id.playbutton)
        	{
        		TCPClient.message = "button-play";
        		Thread newClientThread = new Thread(new TCPClient());
        		newClientThread.start();
        	}
        	else if(v.getId() == R.id.ffbutton)
        	{
        		TCPClient.message = "button-fwd";
        		Thread newClientThread = new Thread(new TCPClient());
        		newClientThread.start();
        	}
        	else if(v.getId() == R.id.skipforwardbutton)
        	{
        		TCPClient.message = "button-skipforward";
        		Thread newClientThread = new Thread(new TCPClient());
        		newClientThread.start();
        	}
        }
    };

    private class StatusThread extends Thread 
    {   
        public void run() {
            try { 
                SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(MainActivity.me.getBaseContext());
                String serverName = prefs.getString(MainActivity.me.getString(R.string.servernamekey), "htpc");
                int deviceNumber = Integer.parseInt(prefs.getString(MainActivity.me.getString(R.string.devicenumberkey), "0"));
                
                InetAddress serverAddr = InetAddress.getByName(serverName); 
                 
                Log.d("TCP", "C: Connecting..."); 
                Socket socket = new Socket(serverAddr, 40400 + deviceNumber); 
                    try { 
                 	DataInputStream input;
                 	input = new DataInputStream(socket.getInputStream());
                 	String responseLine;
                 	while ((responseLine = input.readLine()) != null) {
                         Log.d("TCP", "S: " + responseLine);
                         lastUpdate = responseLine;
                         mHandler.post(showUpdate);
                         if (responseLine == "EndSession=1") {
                           break;
                         }
                         if(Thread.interrupted())
                        	 break;
                     }
                     
                  } catch(Exception e) { 
                      Log.e("TCP", "S: Error", e); 
                     } finally { 
                       socket.close(); 
                     } 
              } catch (Exception e) { 
                   Log.e("TCP", "C: Error", e); 
              } 
        	
        }
    };
    // Create runnable for posting
    final Runnable showUpdate = new Runnable() {
        public void run() {
        	addDebugInfo(lastUpdate);
        }
    };
    
    public void addDebugInfo(String newContent)
    {
    	debugInfoView.setText(newContent + "\n" + debugInfoView.getText());
    }

	class MyGestureDetector extends SimpleOnGestureListener {
		
		@Override
		public boolean onDown(MotionEvent e) {
			// TODO Auto-generated method stub
			return super.onDown(e);
		}
		@Override
		public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
				float velocityY) {
			try {
				if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
					return false;
				// right to left swipe
				if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE
						&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
					Toast.makeText(MainActivity.this, "Left Swipe",
							Toast.LENGTH_SHORT).show();
				} else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE
						&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
					Toast.makeText(MainActivity.this, "Right Swipe",
							Toast.LENGTH_SHORT).show();
				}
			} catch (Exception e) {
				// nothing
			}
			return false;
		}
		@Override
		public boolean onSingleTapConfirmed(MotionEvent e) {
    		TCPClient.message = "button-ok";
    		Thread newClientThread = new Thread(new TCPClient());
    		newClientThread.start();
			return super.onSingleTapConfirmed(e);
		}
		@Override
		public boolean onScroll(MotionEvent e1, MotionEvent e2,
				float distanceX, float distanceY) {
			// TODO Auto-generated method stub
			addDebugInfo("scroll: " + distanceX + ", " + distanceY);
			int scrollTimes = 0;
			if(Math.abs(distanceX) > Math.abs(distanceY))
			{
				scrollTimes = (int) Math.floor(Math.abs(distanceX)/20);
				if(distanceX > 0)
				{
	        		TCPClient.message = "button-left";
				}
				else
				{
	        		TCPClient.message = "button-right";
				}
			}
			else
			{
				scrollTimes = (int) Math.floor(Math.abs(distanceY)/20);
				if(distanceY > 0)
				{
	        		TCPClient.message = "button-up";
				}
				else
				{
	        		TCPClient.message = "button-down";
				}					
			}
			for(int i = 0;i < scrollTimes;i++)
			{
        		Thread newClientThread = new Thread(new TCPClient());
        		newClientThread.start();
			}
			return super.onScroll(e1, e2, distanceX, distanceY);
		}
	}
}
